package utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import net.sf.json.JSONObject;

public class GetHelper {
	
	public static String doHttpGet(String urlStr) {
		
		try {
			URL url = new URL(urlStr);
			
			InputStream inputStream = url.openStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));								
			StringBuilder stringBuilder = new StringBuilder(1000);
			for(String s = reader.readLine(); s != null; s = reader.readLine()) {
				stringBuilder.append(s).append("\n");
			}

			reader.close();
			inputStream.close();

			return stringBuilder.toString();
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String doHttpPost(String urlStr, String param) {
		PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(urlStr);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发生" + e);
            e.printStackTrace();
        }
        //  使用finally块来关闭输出流、输入流
        finally {
            try {
                if(out != null) {
                    out.close();
                }
                if(in != null) {
                    in.close();
                }
            }
            catch(IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
	}
	
	public static String doHttpPost(String urlStr, String param, String safeCheckCode) {
		PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(urlStr);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("safeCheckCode", safeCheckCode);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发生异常" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if(out != null) {
                    out.close();
                }
                if(in != null) {
                    in.close();
                }
            }
            catch(IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
	}
	
	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param outputStr 提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static void httpRequest(String requestUrl, String requestMethod, String outputStr,String safeCheckCode) {
		InputStream inputStream=null;
		InputStreamReader inputStreamReader=null;
		BufferedReader bufferedReader =null;
		HttpURLConnection httpUrlConn=null;
		try {
			URL url = new URL(requestUrl);
			httpUrlConn =  (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);
			if(safeCheckCode!=null&&!"".equals(safeCheckCode)){
				httpUrlConn.setRequestProperty("safeCheckCode", safeCheckCode);
			}
			if("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if(null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
		/*	inputStream = httpUrlConn.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			
			jsonObject = JSONObject.fromObject(buffer.toString());*/
		} catch (ConnectException ce) {
			 System.out.println("发送 POST 请求出现异常！"+ce);
			 ce.printStackTrace(); 
		} catch (Exception e) {
			 System.out.println("发送 POST 请求出现异常！"+e);
	         e.printStackTrace();
		}finally{
			// 释放资源
			try {
				if(bufferedReader!=null){
					bufferedReader.close();
				}
				if(inputStreamReader!=null){
					inputStreamReader.close();
				}
				if(inputStream!=null){
					inputStream.close();
					inputStream = null;
				}
				if(httpUrlConn!=null){
					httpUrlConn.disconnect();
				}
			} catch (IOException e) {
				System.out.println("IO关闭异常"+e);
			}	
		}
	}
	
	
	public static void main(String[] args) {
//		String s = doHttpPost("http://114.215.189.144:8080/YouBoxAPIA1_new/controller", "funcID=0011&terminalID=0", "0dc85019d12c246de36ba3e02fe59234");
//		String s = doHttpPost("http://114.215.189.144:8080/YouBoxAPIA1_new/controller", "funcID=0011&terminalID=0");
//		String s = doHttpPost("http://192.168.1.114:8080/YouBoxAdminAdv/messagePush!send", "");
	}
	
}